package com.example.demojpa.dao;

import org.hibernate.Session;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * ${des}
 * Created by xt on 2017/3/31.
 */
public class SqlDaoAppImpl implements SqlDaoApp {
    @PersistenceContext
    private EntityManager em;


    @Override
    public int executeUpdate(String sql) {
        System.out.println("---------------------");
        EntityManager target = null;
        target = em.getEntityManagerFactory().createEntityManager();
        Session session = target.unwrap(Session.class);
        session.beginTransaction();
        Integer count = 0;
        try {
            count = session.createSQLQuery(sql).executeUpdate();
        } catch (Exception e) {
            session.getTransaction().rollback();
            e.printStackTrace();
            return 0;
        } finally {
            if(session.getTransaction().isActive()){
                session.getTransaction().commit();
            }
            target.close();
        }
//        session.getTransaction().commit();
        return count;
    }
}
